import React from 'react';
import { connect } from 'react-redux';
import * as routerActions from 'react-router-redux';
import { Form, Input, Button, message } from 'antd';
import Api from 'Utils/api';
import UploadVideo from 'Component/CommonComponents/UploadVideo';
import CommonBg from 'Page/DispatchPage/Components/CommonBorder';
import PicturesWall from './Component/UploadMultipleImages';

const FormItem = Form.Item;
const { TextArea } = Input;
class CreateNewPlan extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      isAdd: false,
      id: props.params.id,
      editRecord: '',
      mapInfo: sessionStorage.getItem('mapAddr') ? JSON.parse(sessionStorage.getItem('mapAddr')) : ''
    };
  }
  componentDidMount() {
    this.initForm();
  }
  componentWillMount() {
    const { id } = this.state;
    if (!id) {
      this.setState({ isAdd: true },
      );
    }
  }
  initForm() {
    const { id } = this.state;
    if (id) {
      const api = new Api({
        method: 'GET',
        path: `/archives/${id}`,
        success: (json) => { this.setState({ editRecord: json }); },
        error: (msg) => {
          message.error(msg);
        }
      });
      api.run();
    }
  }
  handleSend() {
    const { id, mapInfo } = this.state;
    const formValue = this.props.form.getFieldsValue();
    this.props.form.validateFieldsAndScroll((err) => {
      if (!err) {
        const currentValue = this.state.editRecord || {};
        let newRecord = { ...currentValue, ...formValue };
        if (id) {
          newRecord.longitude = mapInfo ? mapInfo.lng : this.state.editRecord.longitude;
          newRecord.lartitude = mapInfo ? mapInfo.lat : this.state.editRecord.lartitude;
          const editApi = new Api({
            method: 'PATCH',
            path: `/archives/${id}`,
            data: newRecord,
            success: () => {
              this.props.dispatch(routerActions.goBack());
              sessionStorage.removeItem('MapBeforeInfo');
              sessionStorage.removeItem('mapAddr');
            },
            error: (msg) => {
              message.error(msg);
            }
          });
          editApi.run();
        } else {
          newRecord.longitude = mapInfo.lng;
          newRecord.lartitude = mapInfo.lat;
          console.log(newRecord);
          const addApi = new Api({
            method: 'POST',
            path: '/archives',
            data: newRecord,
            success: (json) => {
              newRecord = json;
              this.props.dispatch(routerActions.goBack());
              sessionStorage.removeItem('MapBeforeInfo');
              sessionStorage.removeItem('mapAddr');
            },
            error: (msg) => {
              message.error(msg);
            }
          });
          addApi.run();
        }
      }
    });
  }
  onEnterMap() {
    const formValue = this.props.form.getFieldsValue();
    const mapBeforeInfo = JSON.stringify(formValue);
    sessionStorage.setItem('MapBeforeInfo', mapBeforeInfo);
    this.props.dispatch(routerActions.push('/system/dispatch/support/special_manage/choose_map'));
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    const formInfo = sessionStorage.getItem('MapBeforeInfo');
    const initialValue = formInfo ? JSON.parse(formInfo) : this.state.editRecord;
    const title = this.state.isAdd ? '新增' : '修改';
    console.log(initialValue);
    return (
      <div>
        <CommonBg
          title={`专题档案${title}`}
          content={
            <div className="Create-new-plan-page">
              <div className="project-wrap">
                <div className="form">
                  <Form>
                    <FormItem
                      label="标题:"
                    >
                      {getFieldDecorator('title', {
                        initialValue: initialValue ? initialValue.title : '',
                        rules: [
                          { required: true, message: '请输入标题' }
                        ] }
                      )(
                        <Input style={{ width: 840 }} placeholder="请输入标题" />
                      )}
                    </FormItem>
                    <FormItem
                      label="地址:"
                    >
                      {getFieldDecorator('address', {
                        initialValue: initialValue ? initialValue.address : '',
                        rules: [
                          { required: true, message: '请选择地址' }
                        ]
                      })(
                        <Input style={{ width: 840 }} placeholder="请在地图上选择地址" disabled />
                      )}
                      <Button onClick={this.onEnterMap.bind(this)} className="map-area">地图选点</Button>
                    </FormItem>
                    <FormItem
                      label="专题简介:"
                    >
                      {getFieldDecorator('introduction', {
                        initialValue: initialValue ? initialValue.introduction : '',
                        rules: [
                          { required: true, message: '请输入专题简介' }
                        ]
                      })(
                        <TextArea style={{ width: 840, height: 150 }} placeholder="请输入专题简介" />
                      )}
                    </FormItem>
                    <FormItem
                      label="图片:"
                    >
                      {getFieldDecorator('picture', {
                        initialValue: initialValue ? initialValue.picture : [],
                      })(
                        <PicturesWall
                          initImg={initialValue.picture ? initialValue.picture : []}
                          isOpen={initialValue.picture !== undefined}
                        />
                      )}
                    </FormItem>
                    <FormItem
                      label="视频:"
                    >
                      {getFieldDecorator('video', {
                        initialValue: initialValue ? parseInt(`${initialValue.video}`, 10) : '',
                      })(
                        <UploadVideo />
                      )}
                    </FormItem>
                  </Form>
                </div>
              </div>
              <div className="btn-bottom">
                <Button className="ok-btn" onClick={this.handleSend.bind(this)}>
                  创建
                </Button>
              </div>
            </div>
          }
        />
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    ...state.routing,
    ...state.chooseMapReducer,
  };
}

export default connect(mapStateToProps)(Form.create()(CreateNewPlan));
